package vip.xiaonuo.modular.common;

import cc.blynk.clickhouse.ClickHouseDataSource;
import cn.hutool.log.Log;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.dbs.core.context.DataSourceContext;

import javax.sql.DataSource;
import java.util.Map;

/**
 * 加载clickhouse数据源到snowy框架的数据源的上下文容器
 * @Author: liu
 * @Date:2022/8/4
 */
@Component
public class LoadClickhouseDatasource implements CommandLineRunner {

    private Log log = Log.get();

    @Value("${clickhouse.url}")
    private String url;

    @Override
    public void run(String... args) throws Exception {
        Map<String, DataSource> dataSources = DataSourceContext.getDataSources();
        ClickHouseDataSource dataSource = new ClickHouseDataSource(url);
        dataSources.put(WdAnalysisConst.CLICKHOUSE_DATASOURCE, dataSource);
        log.info("clickhouse数据源已初始化完成");
    }

    public static ClickHouseDataSource get(){
        ClickHouseDataSource ds =(ClickHouseDataSource) DataSourceContext.getDataSources().get(WdAnalysisConst.CLICKHOUSE_DATASOURCE);
        if(ds == null){
            throw new ServiceException(9, "没有找到clickhouse数据源，导入数据失败");
        }
        return ds;
    }
}
